package top.yaofengqiao.springcloudsimple.auth.biz.infrastructure.repository;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Repository;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.user.model.entity.UserEntity;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.user.repository.IUserRepository;
import top.yaofengqiao.springcloudsimple.auth.biz.infrastructure.dao.SysUserMapper;
import top.yaofengqiao.springcloudsimple.auth.biz.infrastructure.po.SysUserPO;

import javax.annotation.Resource;

/**
 * @author yfq
 * @date 2024/6/1 15:05
 * @description
 */
@Repository
public class UserRepository implements IUserRepository {
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public UserEntity queryByUsername(String username) {
        if (StrUtil.isEmpty(username)) return null;

        SysUserPO sysUserPO = sysUserMapper.selectOne(Wrappers.<SysUserPO>lambdaQuery().eq(SysUserPO::getUsername, username));

        return buildUserEntity(sysUserPO);
    }

    @Override
    public UserEntity queryById(long userId) {
        SysUserPO sysUserPO = sysUserMapper.selectById(userId);

        return buildUserEntity(sysUserPO);
    }

    private UserEntity buildUserEntity(SysUserPO sysUserPO) {
        if (sysUserPO == null) return null;

        return UserEntity.builder()
                .id(sysUserPO.getId())
                .username(sysUserPO.getUsername())
                .password(sysUserPO.getPassword())
                .nickname(sysUserPO.getNickname())
                .remark(sysUserPO.getRemark())
                .deptId(sysUserPO.getDeptId())
                .postIds(sysUserPO.getPostIds())
                .email(sysUserPO.getEmail())
                .mobile(sysUserPO.getMobile())
                .sex(sysUserPO.getSex())
                .avatar(sysUserPO.getAvatar())
                .status(sysUserPO.getStatus())
                .loginIp(sysUserPO.getLoginIp())
                .loginDate(sysUserPO.getLoginDate())
                .build();
    }
}
